/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年12月25日         cassie
 */

package com.coocaa.launcher.pattern.normal;

import android.content.Intent;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.coocaa.launcher.framework.launcherhost.LauncherHostView.LauncherHostPageView;
import com.coocaa.launcher.framework.launcherhost.LauncherHostViewBoundaryEvent;
import com.coocaa.launcher.framework.launcherhost.LauncherHostViewBoundaryEvent.IHostViewBoundaryEventListener;
import com.coocaa.launcher.framework.launcherhost.LauncherHostViewController;
import com.coocaa.launcher.framework.launcherhost.statusbar.StatusBarHostView;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.APP_ITEM_TYPE;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppEntryData;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppFolderData;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppItemData;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppShortCutData;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppWidgetData;
import com.coocaa.launcher.framework.manager.homekey.HomeKeymanager;
import com.coocaa.launcher.pattern.normal.allapp.AllLocalAppView;
import com.coocaa.launcher.pattern.normal.allapp.AllLocalAppView.AllAppMenuListener;
import com.coocaa.launcher.pattern.normal.desktop.DesktopController;
import com.coocaa.launcher.pattern.normal.desktop.DesktopView;
import com.coocaa.launcher.pattern.normal.hotseat.HotSeatView.HotSeatState;
import com.coocaa.launcher.pattern.normal.pick.PickResultListener;
import com.coocaa.launcher.pattern.normal.statusbar.StatusBar;
import com.coocaa.launcher.util.PathConstants;
import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.app.framework.app.LiteAppApplication.ContentAppChangedReceiver.ContentAppChangedReceiverListener;
import com.coocaa.x.app.framework.receiver.HomeKeyReceiver;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.tianci.appstore.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cassie
 * @version TODO (write something)
 * @ClassName NormalController
 * @Description TODO 所有 获取数据、刷新UI、处理UI事件 的代码都在这个类中进行处理
 * @date 2014年12月26日
 */
public class NormalController extends LauncherHostViewController implements
        HomeKeyReceiver.IHomeKeyBroadcastListener, ContentAppChangedReceiverListener {
    /**
     * @Fields serialVersionUID TODO(write something)
     */
    private List<LauncherHostPageView> list = null;
    /**
     * DesktopView - 整个桌面view，包括左侧菜单项，下方常用位
     */
    // private DesktopView desktopView = null;
    private DesktopController desktopController = null;
    private AllLocalAppView allAppView = null;
    private boolean allAppViewAdded = false;
    private StatusBarHostView statusbar = null;
    private String crtViewName;
    private String shownViewName;
    private DesktopView desktopView;
    private boolean isSwitchToAlApp = false;
    private boolean isCooCaa5Ver = false;

    public NormalController() {
        super("pattern.normal");
        // enableNotifyPackageAdded(false);
        // TODO Auto-generated constructor stub
        new Thread(new Runnable() {
            @Override
            public void run() {
                LiteAppApplication.addContentAppChangedReceiverListener(NormalController.this);
            }
        }).start();
    }

    @Override
    protected List<LauncherHostPageView> inflate() {
        // TODO Auto-generated method stub
        return list;
    }

    @Override
    protected void onCreate(LauncherHostViewContext context) {
        super.onCreate(context);
        list = new ArrayList<LauncherHostPageView>();
        if (statusbar == null)
            statusbar = new StatusBar(mContext);
        setStatusBar(statusbar);
        initDesktopView();
        initAllAppView();
        isCooCaa5Ver = HomeKeymanager.getInstance().isCooCaaVer5();
        if (isCooCaa5Ver) {
            HomeKeymanager.getInstance().registerHomeKeyListener(this);
        }

        //move to init hostCOntext
//        if (LiteAppApplication.canShowGuide()) {
//            InputStream in = null;
//            BufferedReader br = null;
//            try {
//                String line = null;
//                int pos = 0;
//                in = ConfigUtils.getCurrnetConfig("launcher_default_hotapps.config", mContext);
//                br = new BufferedReader(new InputStreamReader(in));
//                while ((line = br.readLine()) != null) {
//                    JSONObject jobj = JSON.parseObject(line);
//                    String mainActivity = jobj.getString("mainActivity");
//                    String packageName = jobj.getString("packageName");
//
//                    PackageManager pm = mContext.getPackageManager();
//                    try {
//                        ActivityInfo ai = pm.getActivityInfo(new ComponentName(packageName,
//                                mainActivity), 0);
//                        AppEntryData entry = new AppEntryData();
//                        entry.setPackageName(packageName);
//                        entry.setActivityName(mainActivity);
//                        entry.setMainActivity(mainActivity);
//                        entry.setId(UUID.randomUUID().toString());
//                        entry.setTitle(String.valueOf(ai.loadLabel(pm)));
//                        entry.setType(APP_ITEM_TYPE.APP_ENTRY_TYPE.toString());
//                        LayoutExtra extra = new LayoutExtra();
//                        extra.setPreseted(true);
//                        extra.setPosition(pos++);
//                        entry.setLayoutExtra(extra.toString());
//                        hostContext.addAppEntryData(entry, "", true);
//                    } catch (NameNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                }
//            } catch (Exception e1) {
//                e1.printStackTrace();
//            } finally {
//                if (in != null)
//                    try {
//                        in.close();
//                    } catch (IOException e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//                if (br != null)
//                    try {
//                        br.close();
//                    } catch (IOException e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//            }
//        }
    }

    private void initDesktopView() {
        desktopController = new DesktopController(mContext);
        desktopView = desktopController.getView();
        desktopView.setDefault(true);
        desktopView.setHotSeatExecutor(hotSeatExecutor);
        desktopView.setBoundaryDetector(boundaryDetector);
        crtViewName = desktopView.getName();
        shownViewName = desktopView.getName();
        list.add(desktopView);
        List<AppItemData> dataList = hostContext.getAllItems(true);
        desktopView.updateHotSeatList(dataList);
        desktopView.setPickResultListener(pickResultListener);
    }

    private void initAllAppView() {
//        new Thread() {
//            @Override
//            public void run() {
        allAppView = new AllLocalAppView(mContext);
        list.add(allAppView);
        allAppView.setBoundaryDetector(boundaryDetector);
        allAppView.setMenuListener(menuListener);
//        addLauncherHostPageView(allAppView);
        allAppViewAdded = true;
        LogUtils.d("switch", "************All app view added = true");
//            }
//        }.start();
        // list.add(allAppView);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        statusbar = null;
        if (desktopController != null) {
            desktopController.destory();
        }

        if (isCooCaa5Ver) {
            HomeKeymanager.getInstance().unRegisterHomeKeyListener(this);
        }
        LiteAppApplication.removeContentAppChangedReceiverListener(NormalController.this);
    }

    @Override
    protected AppFolderData onAppFolderAdded(AppFolderData data) {
        // TODO Auto-generated method stub
        if (desktopController == null)
            return null;
        if (desktopController.getView().addHotSeatItem(data, "", false))
            return super.onAppFolderAdded(data);
        return null;
    }

    @Override
    protected boolean onAppFolderRemoved(AppFolderData data) {
        // TODO Auto-generated method stub
        return desktopController.getView().removeHotSeatItem(data, "");
    }

    @Override
    protected AppShortCutData onShortCutAdded(AppShortCutData data) {
        // TODO Auto-generated method stub
        if (desktopController.getView().addHotSeatItem(data, "", false))
            return super.onShortCutAdded(data);
        return null;
    }

    @Override
    protected boolean onShortCutRemoved(AppShortCutData data) {
        // TODO Auto-generated method stub
        return desktopController.getView().removeHotSeatItem(data, "");
    }

    @Override
    protected boolean onAppItemInVisiableChanged(AppItemData data, boolean v) {
        if (v)
            return desktopController.getView().removeHotSeatItem(data, PathConstants.RemoveShortcutPath.UNPLUGIN_SDCARD.toString());
        else
            return desktopController.getView().addHotSeatItem(data, "", true);
    }

    @Override
    protected AppEntryData onAppEntryAdded(AppEntryData data, String path, boolean binit) {
        // TODO Auto-generated method stub
        LogUtils.d("add_entry", "OnAppEntryAdded called!!!");
        if (desktopController.getView().addHotSeatItem(data, path, binit))
            return data;
        return null;
    }

    @Override
    protected boolean onAppEntryRemoved(AppEntryData data, String path) {
        // TODO Auto-generated method stub
        return desktopController.getView().removeHotSeatItem(data, path);
    }

    public static boolean handleKey = true;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        LogUtils.d("key", "normal controller - onkeydown, keyCode = " + keyCode + ", handleKey = "
                + handleKey);
        if (!handleKey)
            return true;
        if (desktopController != null && crtViewName == desktopController.getView().getName()) {
            // 如果sidebar处于显示状态，接到返回键则隐藏sidebar
            if (desktopController.processKeyDown(keyCode))
                return true;
        } else if (allAppView != null && crtViewName == allAppView.getName()) {
            if (allAppView.processKeyDown(keyCode))
                return true;
        }

        if (keyCode == KeyEvent.KEYCODE_HOME && isCooCaa5Ver) {
            if (HomeKeymanager.getInstance().getAppStoreIsHomePage()) {
                responseHomekey();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private HotSeatExecutor hotSeatExecutor = new HotSeatExecutor() {
        @Override
        public void sendRemoveEntryAction(AppEntryData data) {
            // TODO Auto-generated method stub

            hostContext.removeAppEntryData(data,
                    PathConstants.RemoveShortcutPath.SHORTCUT_EDIT.toString());
        }

        @Override
        public void sendRemoveShortcutAction(AppShortCutData data) {
            // TODO Auto-generated method stub
            hostContext.removeAppShortcutData(data);
        }

        @Override
        public void sendRemoveWidgetAction(AppWidgetData data) {
            // TODO Auto-generated method stub
            hostContext.removeAppWidgetData(data);
        }

        @Override
        public void sendRemoveFolderAction(AppFolderData data) {
            // TODO Auto-generated method stub
            hostContext.removeAppFolderData(data);
        }
    };

    public interface HotSeatExecutor {
        public void sendRemoveEntryAction(AppEntryData data);

        public void sendRemoveShortcutAction(AppShortCutData data);

        public void sendRemoveWidgetAction(AppWidgetData data);

        public void sendRemoveFolderAction(AppFolderData data);
    }

    private Animation inUpDownAnim;
    private Animation outUpDownAnim;
    private Animation inDownUpAnim;
    private Animation outDownUpAnim;

    private void initAnimation() {
        if (inUpDownAnim == null) {
            // inUpDownAnim = new AlphaAnimation(0, 1.0f);
            // inUpDownAnim.setDuration(UIConfig.AllAppMenuAnimDuration);
        }
        if (outUpDownAnim == null) {
            outUpDownAnim = AnimationUtils.loadAnimation(mContext, R.anim.out_updown);
            outUpDownAnim.setDuration(UIConfig.AllAppMenuAnimDuration);
        }
        if (inDownUpAnim == null) {
            inDownUpAnim = AnimationUtils.loadAnimation(mContext, R.anim.in_downup);
            inDownUpAnim.setDuration(UIConfig.AllAppMenuAnimDuration);
        }
        if (outDownUpAnim == null) {
            outDownUpAnim = new AlphaAnimation(1.0f, 0);
            outDownUpAnim.setDuration(UIConfig.AllAppMenuAnimDuration);
        }
    }

    private IHostViewBoundaryEventListener switchPageListener = new IHostViewBoundaryEventListener() {
        @Override
        public void onHostViewBoundaryEventComplete(LauncherHostViewBoundaryEvent event) {
            // TODO Auto-generated method stub
            LogUtils.d("key", "     switch complete, set handleKey true");
            handleKey = true;
            shownViewName = crtViewName;
            if (crtViewName == desktopController.getView().getName()) {
                desktopController.resetHotSeatFocus();
            } else {
                allAppView.resetFocus();
            }
        }

        @Override
        public void onHostViewBoundaryEventCompleteFailed(LauncherHostViewBoundaryEvent event) {
            // TODO Auto-generated method stub
            LogUtils.d("key", "     switch failed, set handleKey true");
            handleKey = true;
            crtViewName = shownViewName;
        }
    };

    private BoundaryDetector boundaryDetector = new BoundaryDetector() {
        @Override
        public void switchToHotSeat() {
            // TODO Auto-generated method stub
            LogUtils.d("switch", "to hotSeat, crtName = " + crtViewName);
            if (shownViewName == desktopController.getView().getName())
                return;
            LogUtils.d("key", "------switch to hotseat, handleKey = false");
            handleKey = false;
            isSwitchToAlApp = false;
            LauncherHostViewBoundaryEvent event = new LauncherHostViewBoundaryEvent();
            initAnimation();
            event.setInAnimation(null);
            event.setOutAnimation(outUpDownAnim);
            event.setToLauncherHostPageView(desktopController.getView());
            crtViewName = desktopController.getView().getName();
            commitBoundaryEvent(event, switchPageListener);
        }

        @Override
        public void switchToAllApp() {
            // TODO Auto-generated method stub
            LogUtils.d("switch", "to allapp, crtName = " + crtViewName);
            if (allAppView == null || allAppViewAdded == false) {
                LogUtils.d("switch", "all view == null || not added !!!");
                return;
            }
            if (shownViewName == allAppView.getName())
                return;

            LogUtils.d("key", "------switch to allapp, handleKey = false");
            handleKey = false;
            isSwitchToAlApp = true;
            allAppView.readyToShow();
            LauncherHostViewBoundaryEvent event = new LauncherHostViewBoundaryEvent();
            initAnimation();
            event.setInAnimation(inDownUpAnim);
            event.setOutAnimation(outDownUpAnim);
            event.setToLauncherHostPageView(allAppView);
            crtViewName = allAppView.getName();
            commitBoundaryEvent(event, switchPageListener);
        }
    };

    public interface BoundaryDetector {
        public void switchToAllApp();

        public void switchToHotSeat();
    }

    private AllAppMenuListener menuListener = new AllAppMenuListener() {
        @Override
        public void onAppUninstall(final AppItemData data) {
            // TODO Auto-generated method stub
            if (data.getType().equals(APP_ITEM_TYPE.APP_ENTRY_TYPE.toString())) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            XServiceManager.getLitePMService().uninstall(
                                    ((AppEntryData) data).getPackageName(), false);
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }

        @Override
        public boolean onAppAddToHotSeat(AppItemData data) {
            // TODO Auto-generated method stub
            if (data.getType().equals(APP_ITEM_TYPE.APP_ENTRY_TYPE.toString())) {
                return hostContext.addAppEntryData((AppEntryData) data,
                        PathConstants.AddShortcutPath.ALL_APPS_MENU.toString(), false);
            }
            return false;
        }
    };

    private PickResultListener pickResultListener = new PickResultListener() {
        @Override
        public void onPickResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            onActivityResult(requestCode, resultCode, data);
        }
    };

    private void responseHomekey() {

        LogUtils.i("normalController", "responseHomekey");
        if (!isViewCovered(desktopView) && isCooCaa5Ver) {
            if (desktopView.getHotSeat().getCurrentState() == HotSeatState.EDIT) {
                desktopView.getHotSeat().exitEditState();
            } else if (desktopView.getHotSeat().getCurrentState() == HotSeatState.NORMAL) {
                if (desktopView.getHotSeat().getVisibility() != View.VISIBLE) {
                    desktopController.getmItemContainer().hideLayout();
                } else if (desktopView.getHotSeat().getVisibility() == View.VISIBLE) {
                    Intent itt2 = new Intent();
                    itt2.setPackage("com.tianci.taskmanager");
                    itt2.setAction("com.tianci.taskmanager.recent.action.TOGGLE_RECENTS");
//                    itt2.setClassName("com.android.systemui",
//                            "com.android.systemui.recent.RecentsActivity");
                    itt2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        mContext.startActivity(itt2);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (isCooCaa5Ver) {
            if (desktopView.getHotSeat().getCurrentState() == HotSeatState.EDIT) {
                desktopView.getHotSeat().exitEditState();
            }

            if (desktopView.getHotSeat().getVisibility() != View.VISIBLE) {
                desktopController.getmItemContainer().hideLayout();
            }

            if (isSwitchToAlApp == true) {
                boundaryDetector.switchToHotSeat();
            }
        }

    }

    private boolean isViewCovered(final View view) {
        if (view == null || view.getVisibility() != View.VISIBLE || view.isShown() == false) {
            return true;
        }

        return false;
    }

    @Override
    public void homeKeyReceiverCallBack() {
        // TODO Auto-generated method stub

        LogUtils.i("normalController", "homeKeyReceiverCallBack");
        if (isCooCaa5Ver) {
            if (desktopView.getHotSeat().getCurrentState() == HotSeatState.EDIT) {
                desktopView.getHotSeat().exitEditState();
            }

            if (desktopView.getHotSeat().getVisibility() != View.VISIBLE) {
                desktopController.getmItemContainer().hideLayout();
            }

            if (isSwitchToAlApp == true) {
                boundaryDetector.switchToHotSeat();
            }
        }
    }

    @Override
    public void onAction(Intent i) {
        if (allAppView != null) {
            allAppView.appListChanged();
        }
    }
}
